package service

import (
	"context"
	"errors"
	"fmt"
	"order_srv/basic/orderproto"
	"order_srv/handler/dao"
	"order_srv/handler/models"
	"strconv"
	"time"
)

// AcceptOrder 接单操作
func (s *Server) AcceptOrder(ctx context.Context, req *__.AcceptOrderReq) (*__.AcceptOrderResp, error) {
	//验证请求参数
	if req.OrderId == 0 {
		return &__.AcceptOrderResp{
			Code:    400,
			Message: "订单ID不能为空",
		}, nil
	}
	if req.OperatorId == 0 {
		return &__.AcceptOrderResp{
			Code:    400,
			Message: "操作员ID不能为空",
		}, nil
	}
	if req.OperatorType == 0 {
		return &__.AcceptOrderResp{
			Code:    400,
			Message: "操作员类型不能为空",
		}, nil
	}

	//执行接单操作
	err := dao.AcceptOrder(ctx, req.OrderId, int32(req.OperatorType), int32(req.OperatorId), req.Reason)
	if err != nil {
		return &__.AcceptOrderResp{
			Code:    500,
			Message: fmt.Sprintf("接单失败：%v", err),
		}, nil
	}
	//更新操作员活跃时间
	err = dao.UpdateOperatorActivity(strconv.Itoa(int(req.OperatorId)))
	if err != nil {
		return nil, errors.New("更新操作员活跃时间失败")
	}

	// 计算响应时间
	return &__.AcceptOrderResp{
		Code:       200,
		Message:    "接单成功",
		OrderId:    req.OrderId,
		OrderNo:    "", // 可以从数据库查询获取
		AcceptedAt: time.Now().Format(time.RFC3339),
	}, nil
}

// RejectOrder 拒绝订单
func (s *Server) RejectOrder(ctx context.Context, req *__.RejectOrderReq) (*__.RejectOrderResp, error) {
	// 验证请求参数
	if req.OrderId == 0 {
		return &__.RejectOrderResp{
			Code:    400,
			Message: "订单ID不能为空",
		}, nil
	}
	if req.OperatorId == 0 {
		return &__.RejectOrderResp{
			Code:    400,
			Message: "操作员ID不能为空",
		}, nil
	}
	if req.OperatorType == 0 {
		return &__.RejectOrderResp{
			Code:    400,
			Message: "操作员类型不能为空",
		}, nil
	}
	if req.Reason == "" {
		return &__.RejectOrderResp{
			Code:    400,
			Message: "拒绝原因不能为空",
		}, nil
	}

	// 执行拒绝操作
	err := dao.RejectOrder(ctx, req.OrderId, int32(req.OperatorType), int32(req.OperatorId), req.Reason)
	if err != nil {
		return &__.RejectOrderResp{
			Code:    500,
			Message: fmt.Sprintf("拒绝订单失败: %v", err),
		}, nil
	}

	// 更新操作员活跃时间
	err = dao.UpdateOperatorActivity(strconv.Itoa(int(req.OperatorId)))
	if err != nil {
		return nil, errors.New("更新操作员活跃时间失败")
	}

	// 计算响应时间
	return &__.RejectOrderResp{
		Code:       200,
		Message:    "拒绝订单成功",
		OrderId:    req.OrderId,
		OrderNo:    "", // 可以从数据库查询获取
		RejectedAt: time.Now().Format(time.RFC3339),
	}, nil
}

// GetPendingOrders 获取待处理订单
func (s *Server) GetPendingOrders(ctx context.Context, req *__.GetPendingOrdersReq) (*__.GetPendingOrdersResp, error) {
	// 设置默认值
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}
	if pageSize > 100 {
		pageSize = 100 // 限制最大页面大小
	}

	status := req.Status
	if status == 0 {
		status = 0 // 默认获取待确认订单
	}

	//获取待处理订单
	orders, total, err := dao.GetPendingOrders(ctx, page, pageSize, status, int32(req.OperatorId))
	if err != nil {
		return &__.GetPendingOrdersResp{
			Code:    500,
			Message: fmt.Sprintf("获取待处理订单失败：%v", err),
		}, nil
	}
	//转换为proto格式
	var protoOrders []*__.OrderInfo
	for _, order := range orders {
		protoOrder := s.convertOrderToProto(order)
		protoOrders = append(protoOrders, protoOrder)
	}
	return &__.GetPendingOrdersResp{
		Code:     200,
		Message:  "获取待处理订单成功",
		Orders:   protoOrders,
		Total:    total,
		Page:     page,
		PageSize: pageSize,
	}, nil

}

// AssignOrder 分配订单
func (s *Server) AssignOrder(ctx context.Context, req *__.AssignOrderReq) (*__.AssignOrderResp, error) {
	// 验证请求参数
	if req.OrderId == 0 {
		return &__.AssignOrderResp{
			Code:    400,
			Message: "订单ID不能为空",
		}, nil
	}
	if req.AssignedTo == "" {
		return &__.AssignOrderResp{
			Code:    400,
			Message: "被分配人不能为空",
		}, nil
	}
	if req.AssignedBy == "" {
		return &__.AssignOrderResp{
			Code:    400,
			Message: "分配人不能为空",
		}, nil
	}

	// 执行分配操作
	err := dao.AssignOrder(ctx, req.OrderId, req.AssignedTo, req.AssignedBy, req.AssignmentNote)
	if err != nil {
		return &__.AssignOrderResp{
			Code:    500,
			Message: fmt.Sprintf("分配订单失败: %v", err),
		}, nil
	}

	// 更新操作员活跃时间
	err = dao.UpdateOperatorActivity(req.AssignedTo)
	if err != nil {
		return nil, errors.New("更新操作员活跃时间失败")
	}

	return &__.AssignOrderResp{
		Code:       200,
		Message:    "分配订单成功",
		OrderId:    req.OrderId,
		AssignedTo: req.AssignedTo,
		AssignedAt: time.Now().Format(time.RFC3339),
	}, nil
}

// GetOrderAcceptanceStats 获取接单统计
func (s *Server) GetOrderAcceptanceStats(ctx context.Context, req *__.GetOrderAcceptanceStatsReq) (*__.GetOrderAcceptanceStatsResp, error) {
	// 获取统计数据
	stats, err := dao.GetOrderAcceptanceStats(ctx, strconv.Itoa(int(req.OperatorId)), req.StartDate, req.EndDate)
	if err != nil {
		return &__.GetOrderAcceptanceStatsResp{
			Code:    500,
			Message: fmt.Sprintf("获取接单统计失败: %v", err),
		}, nil
	}

	return &__.GetOrderAcceptanceStatsResp{
		Code:              200,
		Message:           "获取接单统计成功",
		TotalOrders:       stats["total_orders"].(int64),
		AcceptedOrders:    stats["accepted_orders"].(int64),
		RejectedOrders:    stats["rejected_orders"].(int64),
		PendingOrders:     stats["pending_orders"].(int64),
		AcceptanceRate:    stats["acceptance_rate"].(float64),
		AverageAcceptTime: stats["average_accept_time"].(int64),
		TodayOrders:       stats["today_orders"].(int64),
		TodayAccepted:     stats["today_accepted"].(int64),
	}, nil
}

// BatchAcceptOrders 批量接单
func (s *Server) BatchAcceptOrders(ctx context.Context, req *__.BatchAcceptOrdersReq) (*__.BatchAcceptOrdersResp, error) {
	// 验证请求参数
	if len(req.OrderIds) == 0 {
		return &__.BatchAcceptOrdersResp{
			Code:    400,
			Message: "订单ID列表不能为空",
		}, nil
	}
	if req.OperatorId == 0 {
		return &__.BatchAcceptOrdersResp{
			Code:    400,
			Message: "操作员ID不能为空",
		}, nil
	}
	if req.OperatorType == 0 {
		return &__.BatchAcceptOrdersResp{
			Code:    400,
			Message: "操作员类型不能为空",
		}, nil
	}

	// 执行批量接单
	successCount, failedCount, failedOrders, err := dao.BatchAcceptOrders(
		ctx, req.OrderIds, int32(req.OperatorId), int32(req.OperatorType), req.Reason)
	if err != nil {
		return &__.BatchAcceptOrdersResp{
			Code:    500,
			Message: fmt.Sprintf("批量接单失败: %v", err),
		}, nil
	}

	// 更新操作员活跃时间
	err = dao.UpdateOperatorActivity(strconv.Itoa(int(req.OperatorId)))
	if err != nil {
		return nil, errors.New("更新操作员活跃时间失败")
	}

	return &__.BatchAcceptOrdersResp{
		Code:         200,
		Message:      "批量接单完成",
		SuccessCount: int32(successCount),
		FailedCount:  int32(failedCount),
		FailedOrders: failedOrders,
	}, nil
}

// BatchRejectOrders 批量拒绝订单
func (s *Server) BatchRejectOrders(ctx context.Context, req *__.BatchRejectOrdersReq) (*__.BatchRejectOrdersResp, error) {
	// 验证请求参数
	if len(req.OrderIds) == 0 {
		return &__.BatchRejectOrdersResp{
			Code:    400,
			Message: "订单ID列表不能为空",
		}, nil
	}
	if req.OperatorId == 0 {
		return &__.BatchRejectOrdersResp{
			Code:    400,
			Message: "操作员ID不能为空",
		}, nil
	}
	if req.OperatorType == 0 {
		return &__.BatchRejectOrdersResp{
			Code:    400,
			Message: "操作员类型不能为空",
		}, nil
	}
	if req.Reason == "" {
		return &__.BatchRejectOrdersResp{
			Code:    400,
			Message: "拒绝原因不能为空",
		}, nil
	}

	// 执行批量拒绝
	successCount, failedCount, failedOrders, err := dao.BatchRejectOrders(
		ctx, req.OrderIds, int32(req.OperatorId), int32(req.OperatorType), req.Reason)
	if err != nil {
		return &__.BatchRejectOrdersResp{
			Code:    500,
			Message: fmt.Sprintf("批量拒绝订单失败: %v", err),
		}, nil
	}

	// 更新操作员活跃时间
	err = dao.UpdateOperatorActivity(strconv.Itoa(int(req.OperatorId)))
	if err != nil {
		return nil, errors.New("更新操作员活跃时间失败")
	}

	return &__.BatchRejectOrdersResp{
		Code:         200,
		Message:      "批量拒绝订单完成",
		SuccessCount: int32(successCount),
		FailedCount:  int32(failedCount),
		FailedOrders: failedOrders,
	}, nil
}

// GetOrderByStatus 根据状态获取订单
func (s *Server) GetOrdersByStatus(ctx context.Context, req *__.GetOrdersByStatusReq) (*__.GetOrdersByStatusResp, error) {
	//设置默认值
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}
	if pageSize >= 100 {
		pageSize = 100
	}

	//获取订单列表
	orders, total, err := dao.GetOrdersByStatus(ctx, req.Status, page, pageSize)
	if err != nil {
		return &__.GetOrdersByStatusResp{
			Code:    500,
			Message: fmt.Sprintf("获取订单列表失败：%v", err),
		}, nil
	}

	//转换为proto格式
	var protoOrders []*__.OrderInfo
	for _, order := range orders {
		protoOrder := s.convertOrderToProto(order)
		protoOrders = append(protoOrders, protoOrder)
	}

	return &__.GetOrdersByStatusResp{
		Code:     200,
		Message:  "获取订单列表成功",
		Orders:   protoOrders,
		Total:    total,
		Page:     page,
		PageSize: pageSize,
	}, nil
}

// convertOrderToProto 将Order模型转换为proto格式
func (s *Server) convertOrderToProto(order models.Order) *__.OrderInfo {
	protoOrder := &__.OrderInfo{
		Id:              order.ID,
		OrderNo:         order.OrderNo,
		OrderType:       int32(order.OrderType),
		TenantId:        order.TenantID,
		LandlordId:      order.TenantID,
		PropertyId:      order.PropertyID,
		AgentId:         order.AgentID,
		OrderStatus:     int32(order.OrderStatus),
		PaymentStatus:   int32(order.PaymentStatus),
		TotalAmount:     order.TotalAmount,
		PaidAmount:      order.PaidAmount,
		RefundAmount:    order.RefundAmount,
		LeaseStartDate:  order.LeaseStartDate.Format("2006-01-02"),
		LeaseEndDate:    order.LeaseEndDate.Format("2006-01-02"),
		ActualStartDate: order.ContractURL,
		ActualEndDate:   order.Remark,
		ContractStatus:  int32(order.ContractStatus),
		ContractUrl:     order.ContractURL,
		Remark:          order.Remark,
		CreatedAt:       order.CreatedAt.Format(time.RFC3339),
		UpdatedAt:       order.UpdatedAt.Format(time.RFC3339),
	}

	//处理可选字段
	if order.ActualStartDate != nil {
		protoOrder.ActualStartDate = order.ActualStartDate.Format("2006-01-02")
	}
	if order.ActualEndDate != nil {
		protoOrder.ActualEndDate = order.ActualEndDate.Format("2006-01-02")
	}
	if order.ContractSignedAt != nil {
		protoOrder.ContractSignedAt = order.ContractSignedAt.Format(time.RFC3339)
	}
	if order.CancelTime != nil {
		protoOrder.CancelTime = order.CancelTime.Format(time.RFC3339)
	}
	return protoOrder
}
